package edu.gatech.cs2340.teamrocket.control.networking.dialog;

import java.io.IOException;
import java.net.Socket;
import edu.gatech.cs2340.teamrocket.control.networking.node.Node;
import edu.gatech.cs2340.teamrocket.control.networking.message.Message;

/**
 * Represents a single communication between two Endpoints. An Node can have
 * multiple dialogs with several other Endpoints.
 *
 * @author Joe Tacheron
 */
public class Dialog {

    /**
     * The Node that owns this Dialog
     */
    protected Node endpoint;
    /**
     * The socket thru which we are communicating
     */
    protected Socket socket;
    /**
     * The "speaker" of this Dialog
     */
    protected MessageSender sender;
    /**
     * The "listener" of this Dialog
     */
    protected MessageListener listener;

    /**
     * Start the Dialog and enable it if the Node auto-enables Dialogs.
     *
     * @param endpoint the owning Node
     * @param socket the socket to communicate through
     * @throws IOException
     */
    public Dialog(Node endpoint, Socket socket) throws IOException {
        this.endpoint = endpoint;
        this.socket = socket;
        this.sender = new MessageSender(this, this.socket);
        this.listener = new MessageListener(this, this.socket);
    }

    /**
     * Start the speaking and listening threads
     */
    public void start(){
        new Thread(sender).start();
        new Thread(listener).start();
    }

    /**
     * Stop the two Messaging threads
     */
    public void close(){
        sender.close();
        listener.close();
    }

    /**
     * Have the MessageSender thread send a message
     *
     * @param m Message to send
     */
    public void send(Message m){
        sender.sendMessage(m);
    }

    /**
     * Have the endpoint handle a Message
     *
     * @param m Message to handle
     */
    public void handle(Message m){
        endpoint.handleMessage(this, m);
    }
}